<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 支付宝支付响应处理 (即时到帐)
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: direct.php 272 2012-06-26 03:23:13Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Payment_Respond_Alipay_Direct extends Payment_Respond
{

    /**
     * 获取订单号
     *
     * @return string
     */
    public function get_id()
    {
        return $this->get('out_trade_no');
    }

    /**
     * 获取支付交易号
     *
     * @return string
     */
    public function get_payment_no()
    {
        return $this->get('trade_no');
    }

    /**
     * 获取数据签名
     *
     * @return string
     */
    public function get_sign()
    {
        return $this->get('sign');
    }

    /**
     * 获取订单总金额
     *
     * @return float
     */
    public function get_amount()
    {
        return floatval($this->get('total_fee'));
    }

    /**
     * 获取付款时间
     *
     * @return int
     */
    public function get_time()
    {
        return strtotime($this->get('notify_time'));
    }

    /**
     * 获取付款账号
     *
     * @return string
     */
    public function get_account()
    {
        return $this->get('buyer_email');
    }

    /**
     * 获取支付状态
     *
     * @return int
     */
    public function get_status()
    {
        $status = strtoupper($this->get('trade_status'));
        switch ($status)
        {
            case 'WAIT_BUYER_PAY':
            case 'WAIT_SELLER_CONFIRM_TRADE':   // 初始化
                return Payment::STAT_INITED;
            case 'WAIT_SYS_CONFIRM_PAY':        // 等待付款
                return Payment::STAT_CONFIRMED;
            case 'WAIT_SELLER_SEND_GOODS':      // 已收款，等待发货
                return Payment::STAT_PAID;
            case 'WAIT_BUYER_CONFIRM_GOODS':    // 已发货
                return Payment::STAT_SHIPPED;
            case 'WAIT_SYS_PAY_SELLER':         // 已收货
                return Payment::STAT_RECEIVED;
            case 'TRADE_FINISHED':              // 交易完成
                return Payment::STAT_SUCCEED;
            case 'TRADE_SUCCESS':
                return Payment::STAT_PAID;
            case 'TRADE_CLOSED':                // 交易关闭(未完成)
            default:
                return Payment::STAT_FAILED;
        }
    }

    /**
     * 验证数字签名
     *
     * @throws Exception
     */
    protected function _verify()
    {
        $args = empty($_GET) ? $_POST : $_GET;
        ksort($args);

        $sign = '';
        foreach ($args as $key => $value)
        {
            if ($value != '' AND $key != 'sign' AND $key != 'sign_type')
            {
                $sign .= ($sign == '' ? '' : '&') . "$key=" . $value;
            }
        }
        $sign = md5($sign . $this->_key);

        if ($sign != $this->get_sign())
        {
            throw new Payment_Exception('数字签名认证失败');
        }
    }

}